<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Text Drawing with Color Picker</title>
    <style>
        canvas {
            border: 1px solid #000; /* 为画布添加边框 */
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <br>
    <label for="colorPicker">选择文字颜色:</label>
    <input type="color" id="colorPicker" value="#0000ff">

    <script>
        // 获取 canvas 元素
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // 设置字体样式
        ctx.font = '30px Arial';
        var textColor = '#0000ff'; // 初始文字颜色

        // 鼠标事件变量
        var isDrawing = false;
        var startX, startY;

        // 颜色选择器事件
        var colorPicker = document.getElementById('colorPicker');
        colorPicker.addEventListener('input', function() {
            textColor = colorPicker.value;
            ctx.fillStyle = textColor; // 更新文字颜色
        });

        // 鼠标按下事件
        canvas.addEventListener('mousedown', function(event) {
            isDrawing = true;
            startX = event.offsetX;
            startY = event.offsetY;
        });

        // 鼠标移动事件
        canvas.addEventListener('mousemove', function(event) {
            if (isDrawing) {
                var x = event.offsetX;
                var y = event.offsetY;
                drawText(startX, startY, x, y);
            }
        });

        // 鼠标松开事件
        canvas.addEventListener('mouseup', function(event) {
            isDrawing = false;
        });

        // 绘制文字函数
        function drawText(startX, startY, endX, endY) {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // 计算文字位置
            var text = 'Hello, Canvas!';
            var textWidth = ctx.measureText(text).width;
            var textX = (startX + endX - textWidth) / 2;
            var textY = (startY + endY) / 2;

            // 绘制文字
            ctx.fillText(text, textX, textY);
        }
    </script>
</body>
</html>